<template>
  <div class="question-list">
    <div class="card-header">
      <el-input
        v-model="searchQuery"
        placeholder="搜索题目内容"
        class="search-input"
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
      <div class="header-actions">
        <el-select
          v-model="typeFilter"
          placeholder="题目类型"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="difficultyFilter"
          placeholder="难度"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="item in difficultyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增题目
      </el-button>
    </div>
    <el-card>
      <!-- 题目列表 -->
      <el-table
        :data="questionList"
        style="width: 100%"
        border
        v-loading="loading"
        @row-click="handlePreview"
      >
        <el-table-column prop="index" min-width="80" label="序号" sortable/>
        <el-table-column prop="typeId" label="类型" min-width="85" sortable>
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.typeId)">{{
              getTypeText(row.typeId)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="题目内容"
          min-width="300"
          show-overflow-tooltip sortable
        />
        <el-table-column prop="difficulty" label="难度" min-width="155" sortable>
          <template #default="{ row }">
            <el-rate
              v-model="row.difficulty"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column prop="isPublic" label="公开" min-width="80" sortable />
        <el-table-column prop="createdTime" label="创建时间" min-width="160" sortable />
        <el-table-column label="操作" min-width="130" fixed="right">
          <template #default="{ row }">
            <el-button
              class="but"
              type="primary"
              link
              @click.native.stop="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              class="but"
              type="danger"
              link
              @click.native.stop="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <QuestionPreView ref="questionPreviewRef"/>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { questionApi } from "../../api/questionApi";
import {
  difficultyOptions,
  getTypeTag,
  getTypeText,
  typeOptions,
} from "../../utils/utils";
import QuestionPreView from "../Question/QuestionPreView.vue";

const router = useRouter();
const loading = ref(false);
const questionList = ref([]);
const searchQuery = ref("");
const typeFilter = ref("");
const difficultyFilter = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const questionPreviewRef = ref(null);

// 获取题目列表
const getQuestionPage = async () => {
  loading.value = true;
  try {
    const res = await questionApi.getQuestionPage({
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      content: searchQuery.value,
      typeId: typeFilter.value,
      difficulty: difficultyFilter.value,
    });
    if(res.result.data) {
      questionList.value = res.result.data;
      questionList.value.forEach((o, index) => {
        o.index = index + 1 + pageSize.value * (currentPage.value - 1);
        o.isPublic = o.isPublic ? "是" : "否";
      })
    }
    total.value = res.result.total;
  } catch (error) {
    console.error("获取题目列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getQuestionPage();
};

// 新增题目
const handleAdd = () => {
  router.push("/question/add");
};

// 查看题目
const handleLook = (row) => {
  router.push(`/question/${row.questionId}`);
};

// 编辑题目
const handleEdit = (row) => {
  router.push(`/question/${row.questionId}/edit`);
};

// 预览题目
const handlePreview = (row) => {
  questionPreviewRef.value.handlePreview(row);
};

// 删除题目
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除这道题目吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await questionApi.deleteQuestion(row.questionId);
      ElMessage.success("删除成功");
      getQuestionPage();
    } catch (error) {
      console.error("删除题目失败:", error);
    }
  });
};

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  getQuestionPage();
};

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getQuestionPage();
};

onMounted(() => {
  getQuestionPage();
});
</script>

<style scoped>
.question-list {
  padding: 20px;
}

.search-input {
  width: 20vw;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  gap: 1vw;
  width: 30vw;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>